package com.meetingshow.common.validator;

import java.io.UnsupportedEncodingException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CustomLenValidator implements ConstraintValidator<LenByByte, String> {
    private int min;
    private int max;
    private String encoding;

    public void initialize(LenByByte parameters) {
        min = parameters.min();
        max = parameters.max();
        encoding = parameters.encoding();
        validateParameters();
    }

    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if ( value == null ) {
            return true;
        }
        int length;
        try {
            length = value.getBytes(encoding).length;
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException("Can not get the length of value.");
        }
        return length >= min && length <= max;
    }

    private void validateParameters() {
        if ( min < 0 ) {
            throw new IllegalArgumentException( "The min parameter cannot be negative." );
        }
        if ( max < 0 ) {
            throw new IllegalArgumentException( "The max parameter cannot be negative." );
        }
        if ( max < min ) {
            throw new IllegalArgumentException( "The length cannot be negative." );
        }
    }
}
